package com.itsu.job.rpc.util;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.itsu.job.components.Const;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;

/**
 * @author Jerry.Su
 * @Date 2022/2/8 17:03
 */
@Slf4j
public class RpcCallUtil {

    public static RpcResult call(String url, String requestData, String accessToken) {
        HttpRequest request = HttpUtil.createPost(url).contentType(MediaType.APPLICATION_JSON_VALUE)
                .body(requestData)
                .header(Const.TOKEN_HEADER_KEY, accessToken)
                .disableCache();
        HttpResponse response = request.execute();
        if (response.isOk()) {
            log.debug("Rpc call success with status code {}", response.getStatus());
        } else {
            log.debug("Rpc call fail with status code {}", response.getStatus());
        }
        String body = response.body();
        JSONObject jsonObject = JSONUtil.parseObj(body);
        return JSONUtil.toBean(jsonObject, RpcResult.class);
    }

    public static RpcResult call(String url, String requestData) {
        return call(url, requestData, "");
    }

//    public static void main(String[] args) {
//        System.out.println(call("http://localhost:8849/schedule", "{}"));
//    }
}

